Object
Object 是 JavaScript 的一种数据类型。它用于存储各种键值集合和更复杂的实体。可以通过 Object() 构造函数或者使用对象字面量的方式创建对象。
唯一不从 Object.prototype 继承的对象是那些 null 原型对象。
对象标志特性: 原型,类,扩展标记,null 无对象,undefined 无值
创建对象有四种方法 🤖️
// 1.
const Object1 ={};
// 2.
const Object2 = new Object();
// 3.
function Person() {}
const anotherPerson = Object.create(new Person(), {
myName: { value: "Greg" },
});
// 4.
Person.prototype = { name: 123 };
const o = Object.defineProperty(Person.prototype, "constructor", {
value: "1010",
writable: true,
enumerable: true,
configurable: true,
});
常见的 Object 静态方法 🤖️
Object.assign() 将一个或多个源对象的所有可枚举自有属性的值复制到目标对象中。
const target = { a: 1, b: 2 };
const source = { b: 4, c: 5 };
const returnedTarget = Object.assign(target, source);
console.log(target);
Object.entries() 返回包含给定对象自有可枚举字符串属性的所有 [key, value] 数组。
const object1 = {
a: "somestring",
b: 42,
};
for (const [key, value] of Object.entries(object1)) {
console.log(`${key}: ${value}`);
}
Object.keys() 返回一个包含所有给定对象自有可枚举字符串属性名称的数组。
const object1 = {
a: "somestring",
b: 42,
c: false,
};
console.log(Object.keys(object1));
Object.values() 返回包含给定对象所有自有可枚举字符串属性的值的数组。
const object1 = {
a: "somestring",
b: 42,
c: false,
};
console.log(Object.values(object1));